package org.apache.cordova.appinfo;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

public class AppInfo extends CordovaPlugin {

	private CallbackContext callbackContext;
	
	private Activity activity;
	
	private JSONObject jsonObj = new JSONObject();

	@Override
	public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
		if (this.cordova.getActivity().isFinishing()) {
			return true;
		}
		this.activity = cordova.getActivity();
		setCallbackContext(callbackContext);
		if ("appversion".equals(action)) {
			try {
				jsonObj.put("appversion", getVersion(this.activity));
				callbackContext.success(jsonObj);
			} catch (JSONException e) {
				callbackContext.error(e.getMessage());
				return false;
			}
		}else {
			callbackContext.error(PluginResult.Status.INVALID_ACTION.toString());
			return false;
		}
		return true;
	}
	
	/**
	 * 获取客户端当前版本名
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersion(Context context) {
		String version = "";
		try {
			version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e("获取客户端当前版本名异常", e.getMessage());
		}
		return version;
	}

	public CallbackContext getCallbackContext() {
		return callbackContext;
	}

	public void setCallbackContext(CallbackContext callbackContext) {
		this.callbackContext = callbackContext;
	}
}